using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.ServiceProcess;
using System.Text;
using System.Diagnostics;
using System.Threading;
namespace NETService
{
    public static class NConfigService
    {
        private static string applicationName = System.Diagnostics.Process.GetCurrentProcess().ProcessName.Replace(".vshost", "");
        private static string applicationPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
        private static Mutex mx;
        private static readonly string singleInstance = "Global\\"+NConfigService.applicationName + ".Mutex";
        private static bool IsProcessOpen(string name)
        {
            try
            {
                System.Threading.Mutex.OpenExisting(singleInstance);
                return true;
            }
            catch (WaitHandleCannotBeOpenedException)
            {
                mx = new System.Threading.Mutex(true, singleInstance);

            }
            return false;
        }
        private static bool ServiceCheck(bool autoInstall)
        {
            bool installed = false;

            ServiceController[] controllers = ServiceController.GetServices();
            foreach (ServiceController con in controllers)
            {
                if (con.ServiceName == applicationName)
                {
                    installed = true;
                    break;
                }
            }

            if (installed) return true;

            if (autoInstall)
            {

                ServiceInstaller.InstallService("\"" + applicationPath + "\\" + applicationName + ".exe\" -service",
                    applicationName, ServiceTitle, ServiceDescription, true, false);
            }

            return false;
        }


        public static bool IsService;
        public static string ServiceTitle = "Data Engine Service";
        public static string ServiceDescription = "Data Engine will provide Historian Data for all client applications";
        public static void UseRelativeWorkingDirectory()
        {
            System.IO.Directory.SetCurrentDirectory(System.AppDomain.CurrentDomain.BaseDirectory);
        }
        public static bool MainArgCheck(IConsole ConsoleApp)
        {
            bool ret = true;
            IsService = true;
            if (Environment.CommandLine.Contains("-h") || Environment.CommandLine.Contains("/?"))
            {

                Console.WriteLine("==============> Service Manual <==============");
                Console.WriteLine(" -i: Install service");
                Console.WriteLine(" -u: Uninstall service");
                //Console.WriteLine(" -r: Run service");
                Console.WriteLine(" -h: Help");
                Console.WriteLine("  no agrument: Console mode");
                return true;
            }

            if (IsProcessOpen(NConfigService.applicationName))
            {
                Console.WriteLine("Service has already been run");
                return true;
            }

            if (Environment.CommandLine.Contains("-i"))
            {
                if (ServiceCheck(false) == false)
                {

                    //controller.Start();   
                    bool isSuccess = ServiceInstaller.InstallService("\"" + applicationPath + "\\" + applicationName + ".exe\" -service",
                        applicationName, ServiceTitle, ServiceDescription, true, false);

                    if (isSuccess)
                    {
                        Console.WriteLine("Install Service Successfully");
                        ServiceController controller = new ServiceController(applicationName);

                        if (Environment.CommandLine.Contains("-r"))
                        {
                            if (controller.Status == ServiceControllerStatus.Stopped)
                            {
                                controller.Start();
                                Console.WriteLine("Starting to Run Service");
                            }
                            else
                            {
                                Console.WriteLine("Service is not in Stopped Mode");
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("Install Service FAIL");
                    }
                }
                else
                {
                    Console.WriteLine("Service has already been installed");
                }
            }
            //else if (Environment.CommandLine.Contains("-r"))
            //{
            //    if (ServiceCheck(false))
            //    {
            //        ServiceController controller = new ServiceController(applicationName);
            //        if (controller.Status == ServiceControllerStatus.Stopped)
            //        {
            //            controller.Start();
            //            Console.WriteLine("Starting to Run Service");
            //        }
            //        else
            //        {
            //            Console.WriteLine("Service is not in Stopped Mode");
            //        }

            //    }
            //    else
            //    {
            //        Console.WriteLine("Service has already been uninstalled");
            //    }
            //}
            else if (Environment.CommandLine.Contains("-u"))
            {
                if (ServiceCheck(false))
                {
                    ServiceController controller = new ServiceController(applicationName);
                    if (controller.Status == ServiceControllerStatus.Running) controller.Stop();
                    bool isSuccess = ServiceInstaller.UnInstallService(applicationName);

                    if (isSuccess)
                        Console.WriteLine("Uninstall Service Successfully");
                    else
                    {
                        Console.WriteLine("Uninstall Service FAIL");
                    }
                }
                else
                {
                    Console.WriteLine("Service has already been uninstalled");
                }
            }
            else if (Environment.CommandLine.Contains("-service"))
            {
                ServiceBase[] services = new ServiceBase[] { new ServiceWrapper(ConsoleApp) };
                ServiceBase.Run(services);
            }
            else // Run console
            {
                IsService = false;
                ret = false;
            }
           

            return ret;
        }
        public static void Restart()
        {
            Process process = new Process();
            process.StartInfo.FileName = "cmd";
            process.StartInfo.Arguments = String.Format("/c net stop \"{0}\" & net start \"{0}\"",applicationName);
            process.Start();
        }
    }
}